"""
简化版重启脚本 - 使用端口 8020
"""

import asyncio
import logging
from sqlalchemy.ext.asyncio import create_async_engine, AsyncSession, async_sessionmaker
from sqlalchemy.ext.declarative import declarative_base
from pathlib import Path

# 配置日志
logging.basicConfig(level=logging.INFO, format='%(asctime)s - %(levelname)s - %(message)s')
logger = logging.getLogger(__name__)

# 创建基类
Base = declarative_base()

async def init_db(db_url):
    """初始化数据库连接"""
    logger.info(f"初始化数据库: {db_url}")
    
    # 确保data目录存在
    Path("./data").mkdir(exist_ok=True)
    
    # 创建异步引擎
    if db_url.startswith('sqlite'):
        logger.info("使用SQLite配置")
        engine = create_async_engine(
            db_url,
            echo=False,
            connect_args={"check_same_thread": False}
        )
    else:
        engine = create_async_engine(
            db_url,
            echo=False,
            pool_pre_ping=True,
            pool_recycle=3600
        )
    
    # 创建会话工厂
    async_session_factory = async_sessionmaker(
        engine,
        class_=AsyncSession,
        expire_on_commit=False
    )
    
    return engine, async_session_factory

async def setup_database():
    """设置数据库"""
    # 数据库URL
    db_url = "sqlite+aiosqlite:///./data/app.db"
    
    # 初始化数据库连接
    engine, session_factory = await init_db(db_url)
    
    # 注入到app模块
    import app.core.database
    app.core.database.engine = engine
    app.core.database.async_session_factory = session_factory
    app.core.database.Base = Base
    
    # 创建表
    try:
        # 导入模型
        import app.models
        
        # 直接创建表
        async with engine.begin() as conn:
            await conn.run_sync(Base.metadata.create_all)
        
        logger.info("数据库表创建成功")
        return True
    except Exception as e:
        logger.error(f"创建数据库表失败: {e}")
        return False

async def start_server():
    """启动服务器"""
    port = 8020
    
    # 设置数据库
    success = await setup_database()
    if not success:
        logger.error("数据库设置失败，无法启动服务器")
        return
    
    # 导入应用
    from app.main import create_app
    app = create_app()
    
    # 启动服务器
    import uvicorn
    
    logger.info(f"启动服务器在端口 {port} ...")
    config = uvicorn.Config(
        app=app,
        host="0.0.0.0",
        port=port,
        log_level="info"
    )
    server = uvicorn.Server(config)
    await server.serve()

if __name__ == "__main__":
    logger.info("启动简化版离线语言播放系统 (端口:8020)")
    asyncio.run(start_server())